package com.shanshi.activity;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.bumptech.glide.Glide;


public class DelteListViewItme extends ListView implements AbsListView.OnScrollListener
{

	private static final String TAG = "DeltelistView";

	// private static final int VELOCITY_SANP = 200;
	// private VelocityTracker mVelocityTracker;
	/**
	 * 用户滑动的最小距离
	 */
	private int touchSlop;

	/**
	 * 是否响应滑动
	 */
	private boolean isSliding;

	/**
	 * 手指按下时的x坐标
	 */
	private int xDown;
	/**
	 * 手指按下时的y坐标
	 */
	private int yDown;
	/**
	 * 手指移动时的x坐标
	 */
	private int xMove;
	/**
	 * 手指移动时的y坐标
	 */
	private int yMove;

	private LayoutInflater mInflater;

	private PopupWindow mPopupWindow;
	private int mPopupWindowHeight;
	private int mPopupWindowWidth;

	private Button mDelBtn;
	/**
	 * 为删除按钮提供一个回调接口
	 */
	private DelButtonClickListener mListener;

	/**
	 * 当前手指触摸的View
	 */
	private View mCurrentView;

	/**
	 * 当前手指触摸的位置
	 */
	private int mCurrentViewPos;

	/**
	 * 必要的一些初始化
	 * 
	 * @param context
	 * @param attrs
	 */
	public DelteListViewItme(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		init(context);

		mInflater = LayoutInflater.from(context);
		touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

		View view = mInflater.inflate(R.layout.delte_listview_itme, null);
		mDelBtn = (Button) view.findViewById(R.id.id_item_btn);
		mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		/**
		 * 先调用下measure,否则拿不到宽和高
		 */
		mPopupWindow.getContentView().measure(0, 0);
		mPopupWindowHeight = mPopupWindow.getContentView().getMeasuredHeight();
		mPopupWindowWidth = mPopupWindow.getContentView().getMeasuredWidth();
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev)
	{
		int action = ev.getAction();
		int x = (int) ev.getX();
		int y = (int) ev.getY();
		switch (action)
		
		{

		case MotionEvent.ACTION_DOWN:
			xDown = x;
			yDown = y;
			/**
			 * 如果当前popupWindow显示，则直接隐藏，然后屏蔽ListView的touch事件的下传
			 */
			if (mPopupWindow.isShowing())
			{
				dismissPopWindow();
				return false;
			}
			// 获得当前手指按下时的item的位置
			mCurrentViewPos = pointToPosition(xDown, yDown);
			// 获得当前手指按下时的item
			View view = getChildAt(mCurrentViewPos - getFirstVisiblePosition());
			mCurrentView = view;
			break;
		case MotionEvent.ACTION_MOVE:
			xMove = x;
			yMove = y;
			int dx = xMove - xDown;
			int dy = yMove - yDown;
			/**
			 * 判断是否是从右到左的滑动
			 */
			if (xMove < xDown && Math.abs(dx) > touchSlop && Math.abs(dy) < touchSlop)
			{
				// Log.e(TAG, "touchslop = " + touchSlop + " , dx = " + dx +
				// " , dy = " + dy);
				isSliding = true;
			}
			break;
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev)
	{
		int action = ev.getAction();
		/**
		 * 如果是从右到左的滑动才相应
		 */
		if (isSliding)
		{
			switch (action)
			{

			case MotionEvent.ACTION_MOVE:

				int[] location = new int[2];
				// 获得当前item的位置x与y
				mCurrentView.getLocationOnScreen(location);
				// 设置popupWindow的动画
				mPopupWindow.setAnimationStyle(R.style.popwindow_delete_btn_anim_style);
				mPopupWindow.update();
				mPopupWindow.showAtLocation(mCurrentView, Gravity.LEFT | Gravity.TOP,
						location[0] + mCurrentView.getWidth(), location[1] + mCurrentView.getHeight() / 2
								- mPopupWindowHeight / 2);
				// 设置删除按钮的回调
				mDelBtn.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						if (mListener != null)
						{
							mListener.clickHappend(mCurrentViewPos);
							mPopupWindow.dismiss();
						}
					}
				});
				// Log.e(TAG, "mPopupWindow.getHeight()=" + mPopupWindowHeight);

				break;
			case MotionEvent.ACTION_UP:
				isSliding = false;

			}
			// 相应滑动期间屏幕itemClick事件，避免发生冲突
			return true;
		}else{
			/*******上下滑动响应*******/
			switch (ev.getAction()) {
				case MotionEvent.ACTION_DOWN:

					//获取按下时y坐标
					yDown = (int) ev.getY();
					break;
				case MotionEvent.ACTION_MOVE:

					if(currentState==REFRESHING){
						//如果当前处在滑动状态，则不做处理
						break;
					}
					//手指滑动偏移量
					int deltaY = (int) (ev.getY() - yDown);

					//获取新的padding值
					int paddingTop = -headerViewHeight + deltaY;
					if(paddingTop>-headerViewHeight && getFirstVisiblePosition()==0){
						//向下滑，且处于顶部，设置padding值，该方法实现了顶布局慢慢滑动显现
						headerView.setPadding(0, paddingTop, 0, 0);

						if(paddingTop>=0 && currentState==PULL_REFRESH){
							//从下拉刷新进入松开刷新状态
							currentState = RELEASE_REFRESH;
							//刷新头布局
//                        refreshHeaderView();
						}else if (paddingTop<0 && currentState==RELEASE_REFRESH) {
							//进入下拉刷新状态
							currentState = PULL_REFRESH;
//                        refreshHeaderView();
						}

						return true;//拦截TouchMove，不让listview处理该次move事件,会造成listview无法滑动
					}


					break;
				case MotionEvent.ACTION_UP:
					if(currentState==PULL_REFRESH){
						//仍处于下拉刷新状态，未滑动一定距离，不加载数据，隐藏headView
						headerView.setPadding(0, -headerViewHeight, 0, 0);
					}else if (currentState==RELEASE_REFRESH) {
						//滑倒一定距离，显示无padding值得headcView
						headerView.setPadding(0, 0, 0, 0);
						//设置状态为刷新
						currentState = REFRESHING;

						//刷新头部布局
						refreshHeaderView();

						if(listener!=null){
							//接口回调加载数据
							listener.onPullRefresh();
						}
					}
					break;
			}
		}

		return super.onTouchEvent(ev);
	}


	/**
	 * 隐藏popupWindow
	 */
	private void dismissPopWindow()
	{
		if (mPopupWindow != null && mPopupWindow.isShowing())
		{
			mPopupWindow.dismiss();
		}
	}

	public void setDelButtonClickListener(DelButtonClickListener listener)
	{
		mListener = listener;
	}



	interface DelButtonClickListener
	{
		public void clickHappend(int position);
	}



	/*******************************/
	/**
	 * 头布局
	 */
	private View headerView;

	/**
	 * 头部布局的高度
	 */
	private int headerViewHeight;

	/**
	 * 头部旋转的图片
	 */
	private ImageView iv_arrow;


	/**
	 * 底部布局
	 */
	private View footerView;

	/**
	 * 底部旋转progressbar
	 */
	private ImageView footer_arrow;


	/**
	 * 底部布局的高度
	 */
	private int footerViewHeight;

	private final int PULL_REFRESH = 0;//下拉刷新的状态
	private final int RELEASE_REFRESH = 1;//松开刷新的状态
	private final int REFRESHING = 2;//正在刷新的状态

	/**
	 * 当前下拉刷新处于的状态
	 */
	private int currentState = PULL_REFRESH;

	/**
	 * 当前是否在加载数据
	 */
	private boolean isLoadingMore = false;


	private void init(Context context){
		//设置滑动监听
		setOnScrollListener(this);
		//初始化头布局
		initHeaderView(context);

		//初始化为尾布局
		initFooterView(context);
	}

	/**
	 * 初始化headerView
	 */
	private void initHeaderView(Context context) {
		headerView = View.inflate(getContext(), R.layout.head_custom_listview, null);
		iv_arrow = (ImageView) headerView.findViewById(R.id.iv_arrow);

		Glide.with(context).load(R.drawable.name).centerCrop().into(iv_arrow);

		//测量headView的高度
		headerView.measure(0, 0);
		//获取高度，并保存
		headerViewHeight = headerView.getMeasuredHeight();
		//设置paddingTop = -headerViewHeight;这样，该控件被隐藏
		headerView.setPadding(0, -headerViewHeight, 0, 0);
		//添加头布局
		addHeaderView(headerView);
	}

	//初始化底布局，与头布局同理
	private void initFooterView(Context context) {
		footerView = View.inflate(getContext(), R.layout.foot_custom_listview, null);

		footer_arrow = (ImageView) footerView.findViewById(R.id.footer_arrow);

		Glide.with(context).load(R.drawable.name2).centerCrop().into(footer_arrow);

		footerView.measure(0, 0);
		footerViewHeight = footerView.getMeasuredHeight();
		footerView.setPadding(0, -footerViewHeight, 0, 0);
		addFooterView(footerView);
	}

	/**
	 * 根据currentState来更新headerView
	 */
	private void refreshHeaderView(){
		switch (currentState) {
			case PULL_REFRESH:
				break;
			case RELEASE_REFRESH:
				break;
			case REFRESHING:
				break;
		}
	}

	/**
	 * 完成刷新操作，重置状态,在你获取完数据并更新完adater之后，去在UI线程中调用该方法
	 */
	public void completeRefresh(){
		if(isLoadingMore){
			//重置footerView状态
			footerView.setPadding(0, -footerViewHeight, 0, 0);
			isLoadingMore = false;
		}else {
			//重置headerView状态
			headerView.setPadding(0, -headerViewHeight, 0, 0);
			currentState = PULL_REFRESH;
			iv_arrow.setVisibility(View.VISIBLE);
		}
	}

	private OnRefreshListener listener;
	public void setOnRefreshListener(OnRefreshListener listener){
		this.listener = listener;
	}
	public interface OnRefreshListener{
		void onPullRefresh();
		void onLoadingMore();
	}


	/**
	 * SCROLL_STATE_IDLE:闲置状态，就是手指松开
	 * SCROLL_STATE_TOUCH_SCROLL：手指触摸滑动，就是按着来滑动
	 * SCROLL_STATE_FLING：快速滑动后松开
	 */
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(scrollState==OnScrollListener.SCROLL_STATE_IDLE
				&& getLastVisiblePosition()==(getCount()-1) &&!isLoadingMore){
			isLoadingMore = true;

			footerView.setPadding(0, 0, 0, 0);//显示出footerView
			setSelection(getCount());//让listview最后一条显示出来，在页面完全显示出底布局

			if(listener!=null){
				listener.onLoadingMore();
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

	}


}
